package com.ds.infra.rpc.core.util;

import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * 线程池工具类（带监控和优雅关闭）
 *
 * @author WeiShaoying
 */
@UtilityClass
@Slf4j
public class ThreadPoolUtils {
    public static ThreadPoolExecutor newFixedThreadPool(int coreSize, int maxSize, String poolName) {
        return new ThreadPoolExecutor(
                coreSize,
                maxSize,
                60L, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(1000),
                r -> new Thread(r, "rpc-" + poolName + "-" + r.hashCode()),
                (r, executor) -> {
                    log.warn("Thread pool rejected: {}", poolName);
                    throw new RejectedExecutionException();
                });
    }

    public static void shutdownGracefully(ExecutorService executor, String poolName) {
        try {
            executor.shutdown();
            if (!executor.awaitTermination(10, TimeUnit.SECONDS)) {
                log.warn("Force shutdown thread pool: {}", poolName);
                executor.shutdownNow();
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            log.error("Thread pool shutdown interrupted", e);
        }
    }
}
